package site.jlopen.kuscia.service.data;

import org.secretflow.v1alpha1.kusciaapi.Domaindatagrant.CreateDomainDataGrantRequest;
import org.secretflow.v1alpha1.kusciaapi.Domaindatagrant.CreateDomainDataGrantResponse;
import org.secretflow.v1alpha1.kusciaapi.Domaindatagrant.CreateDomainDataGrantResponseData;
import org.secretflow.v1alpha1.kusciaapi.Domaindatagrant.DomainDataGrant;
import org.secretflow.v1alpha1.kusciaapi.Domaindatagrant.QueryDomainDataGrantRequest;
import org.secretflow.v1alpha1.kusciaapi.Domaindatagrant.QueryDomainDataGrantResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import site.jlopen.kuscia.entity.GrpcApiInfo;
import site.jlopen.kuscia.properties.KusciaAPIProperties;
import site.jlopen.kuscia.rpc.impl.KusciaDomainDataGrantRpcImpl;
import site.jlopen.kuscia.util.UUIDUtils;

@Service
public class KusciaDataGrantManager extends AbstractDataGrantManager{

	private static Logger logger = LoggerFactory.getLogger(KusciaDataManager.class);

	@Override
	public String createDataGrant(GrpcApiInfo apiInfo, String domainId, String grantDomainId, String domaindataId) {
		KusciaAPIProperties apiProperties = apiInfo.convert(apiInfo);
		CreateDomainDataGrantRequest.Builder builder = CreateDomainDataGrantRequest.newBuilder()
				.setDomaindataId(domaindataId)
				.setGrantDomain(grantDomainId)
				.setDomainId(domainId);
        String domaindatagrantId = "dda-id-" + UUIDUtils.random(8);
		builder.setDomaindatagrantId(domaindatagrantId);
		CreateDomainDataGrantRequest request = builder.build();
		CreateDomainDataGrantResponse response = new KusciaDomainDataGrantRpcImpl(apiProperties).createDomainDataGrant(request);
		CreateDomainDataGrantResponseData data = response.getData();
		logger.info("data:{}", data);
		return data.getDomaindatagrantId();
	}

	@Override
	public void updateDataGrant(GrpcApiInfo apiInfo) {
		KusciaAPIProperties apiProperties = apiInfo.convert(apiInfo);
		return;
	}

	@Override
	public void deleteDataGrant(GrpcApiInfo apiInfo) {
		KusciaAPIProperties apiProperties = apiInfo.convert(apiInfo);
		return;
	}

	@Override
	public String queryDataGrant(GrpcApiInfo apiInfo, String domainId, String domaindatagrantId) {
		KusciaAPIProperties apiProperties = apiInfo.convert(apiInfo);
		QueryDomainDataGrantRequest request = QueryDomainDataGrantRequest.newBuilder()
				.setDomainId(domainId)
				.setDomaindatagrantId(domaindatagrantId)
				.build();
		try {
			QueryDomainDataGrantResponse response = new KusciaDomainDataGrantRpcImpl(apiProperties).queryDomainDataGrant(request);
			DomainDataGrant data = response.getData();
			logger.info("data:{}", data);
			return data.getStatus().getPhase();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public void batchQueryDataGrant(GrpcApiInfo apiInfo) {
		KusciaAPIProperties apiProperties = apiInfo.convert(apiInfo);
		
		return;
	}
}
